package leetcode.L124;

class Solution {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int maxSum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        pathSum(root);
        return maxSum;
    }

    //递归得到左右子节点的最大贡献值
    public int pathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftCon = Math.max(pathSum(root.left), 0);
        int rightCon = Math.max(pathSum(root.right), 0);
        //该节点的最大路径和
        int currSum = root.val + leftCon + rightCon;
        maxSum = Math.max(maxSum, currSum);
        return root.val + Math.max(leftCon, rightCon);
    }
}